import json
from datetime import datetime

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

# 视图层面

# 学生信息列表处理函数
from sims.common.biz_exception import BizException
from sims.models import Student


def index(request):
    # 查询全部学生
    students = Student.objects.all()
    # 返回参数
    return render(request, 'student/index.html', {'students': students})


# 新增跳转页面
def add_view(request):
    return render(request, 'student/add.html')


# 添加学生
def add(request):
    request_data = request.body
    request_dict = json.loads(request_data.decode('utf-8'))
    # 学生名称
    insert_stu = Student()
    insert_stu.student_name = request_dict.get('student_name', '')
    insert_stu.student_age = request_dict.get('student_age', '')
    insert_stu.birthday = request_dict.get('birthday', '')
    insert_stu.weight = request_dict.get('weight', '')
    insert_stu.height = request_dict.get('height', '')
    insert_stu.introduce = request_dict.get('introduce', '')
    insert_stu.photo = request_dict.get('photo', '')
    insert_stu.student_class = request_dict.get('student_class', '')
    insert_stu.student_class_name = request_dict.get('student_class_name', '')
    now_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f"新增学生请求参数:{json.dumps(insert_stu, ensure_ascii=False, default=lambda obj: obj.__dict__)}")
    if not Student.objects.filter(student_name=insert_stu.student_name).exists():
        Student.objects.create(
            student_name=insert_stu.student_name,
            student_age=insert_stu.student_age,
            birthday=insert_stu.birthday,
            weight=insert_stu.weight,
            height=insert_stu.height,
            introduce=insert_stu.introduce,
            photo=insert_stu.photo,
            student_class=insert_stu.student_class,
            student_class_name=insert_stu.student_class_name,
            create_time=datetime.strptime(now_date, '%Y-%m-%d %H:%M:%S'))
        ret_obj = {'code': 200, "desc": f"添加学生{insert_stu.student_name}成功"}
        return HttpResponse(json.dumps(ret_obj), status=200, content_type="application/json")
    else:
        ret_obj = {'code': 202, "desc": f"添加学生{insert_stu.student_name}已存在"}
        return HttpResponse(json.dumps(ret_obj), status=202, content_type="application/json")


# 删除学生
def delete(request):
    request_data = request.body
    request_dict = json.loads(request_data.decode('utf-8'))
    student_no = request_dict.get('student_no')
    if not student_no:
        raise Exception('学号不能为空')

    Student.objects.filter(student_no=student_no).delete()
    ret_obj = {'code': 200, "desc": f"学号:{student_no}成功"}
    return HttpResponse(json.dumps(ret_obj), status=200, content_type="application/json")


# 修改页面跳转
def edit_show(request):
    student_no = request.GET.get("student_no")
    if not student_no:
        raise Exception('学号不能为空')
    # 查询学生信息
    student = Student.objects.filter(student_no=student_no)
    if not student:
        raise Exception("未查询到该学生信息")
    return render(request, 'student/edit.html', {'student': student.first()})


def edit(request):
    request_data = request.body
    request_dict = json.loads(request_data.decode('utf-8'))
    student_no = request_dict.get('student_no')
    # 查询学生是否存在
    if not Student.objects.filter(student_no=student_no).exists():
        raise BizException(10001, "未查询到学生信息")
    student_name = request_dict.get('student_name', '')
    student_age = request_dict.get('student_age', '')
    birthday = request_dict.get('birthday', '')
    weight = request_dict.get('weight', '')
    height = request_dict.get('height', '')
    introduce = request_dict.get('introduce', '')
    photo = request_dict.get('photo', '')
    student_class = request_dict.get('student_class', '')
    student_class_name = request_dict.get('student_class_name', '')
    now_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    update_date = datetime.strptime(now_date, '%Y-%m-%d %H:%M:%S')

    try:
        Student.objects.filter(student_no=student_no).update(
            student_name=student_name,
            student_age=student_age,
            birthday=birthday,
            weight=weight,
            height=height,
            introduce=introduce,
            photo=photo,
            student_class=student_class,
            student_class_name=student_class_name,
            create_time=update_date)
        ret_obj = {'code': 200, "desc": f"修改学生{student_name}成功"}
        return HttpResponse(json.dumps(ret_obj), status=200, content_type="application/json")
    except Exception as e:
        print(e)
        raise BizException(10002, "更新失败!")
